const mysql = require('mysql');
const db = require('./mysqlConfig');

// 查询球桌列表
exports.getTableList = (room_id, callback) => {
    let sql = 'SELECT * FROM room_table';
    let params = [];

    if (room_id) {
        sql += ' WHERE room_id = ?';
        params.push(room_id);
    }

    db.query(sql, params, (error, results) => {
        if (error) return callback(error, null);
        callback(null, results);
    });
};

// 根据 table_id 获取球桌详情
exports.getTableById = (table_id, callback) => {
    const sql = 'SELECT * FROM room_table WHERE table_id = ?';
    db.query(sql, [table_id], (error, result) => {
        if (error) return callback(error, null);
        callback(null, result[0]);
    });
};

// 新增球桌
exports.createTable = (tableData, callback) => {
    const { room_id, table_status } = tableData;
    const sql = 'INSERT INTO room_table (room_id, table_status) VALUES (?, ?)';
    db.query(sql, [room_id, table_status], (error, result) => {
        if (error) return callback(error, null);
        callback(null, { table_id: result.insertId, ...tableData });
    });
};

// 更新球桌状态
exports.updateTableStatus = (table_id, newStatus, callback) => {
    const sql = 'UPDATE room_table SET table_status = ? WHERE table_id = ?';
    db.query(sql, [newStatus, table_id], (error, result) => {
        if (error) return callback(error, null);
        callback(null, result.affectedRows > 0);
    });
};

// 删除球桌
exports.deleteTable = (table_id, callback) => {
    const sql = 'DELETE FROM room_table WHERE table_id = ?';
    db.query(sql, [table_id], (error, result) => {
        if (error) return callback(error, null);
        callback(null, result.affectedRows > 0);
    });
};
